﻿using System;
using System.Collections.Generic;
using System.Linq;
using SqlSugar;
using log4net.Core;
using Crossroad.Utils;
using Crossroad.Utils.Extensions;
using Crossroad.Core.Data;
using Crossroad.Core.Exceptions;
using Crossroad.Core.Helper;
using Crossroad.Core.Models;
using Crossroad.System.Common.Model;

namespace Crossroad.System.Common.Service.Impl
{
    /// <summary>
    /// 通用附件
    /// </summary>
    public class AttachmentService: Access<Attachment>, IAttachmentService
    {
        public AttachmentService(
        )
        {
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="method"></param>
        /// <param name="loadRelevantData">是否加载关联数据</param>
        public Pagination<Attachment> GetPaging(
            int pageIndex,
            int pageSize,
            Action<ISugarQueryable<Attachment>> method,
			bool loadRelevantData = true
        )
        {
            var query =  db.Queryable<Attachment>();
            method(query);
            var totalCount = 0;
            var page = new Pagination<Attachment>
            {
                PageIndex = pageIndex,
                PageSize = pageSize,
            };
            page.Records = query.ToPageList(page.PageIndex, page.PageSize, ref totalCount);
            page.TotalCount = totalCount;
			if(loadRelevantData)
				Load(page.Records);

            return page;
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <param name="method"></param>
        /// <param name="loadRelevantData">是否加载关联数据</param>
        /// <returns></returns>
        public  List<Attachment> GetList(
            Action<ISugarQueryable<Attachment>> method,
			bool loadRelevantData = true
        )
        {
            var query =  db.Queryable<Attachment>();
            method(query);
            var list = query.ToList();
			if(loadRelevantData)
				Load(list);

            return list;
        }

        /// <summary>
        /// 获取附件列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="idList"></param>
        /// <param name="loadRelevantData">是否加载关联数据 默认false不加载</param>
        /// <returns></returns>
        public  List<Attachment> GetList<T>(
            IEnumerable<T> idList,
			bool loadRelevantData = false 
        )
        {
            if (idList.IsNullOfEmpty())
                return null;

            var query =  db.Queryable<Attachment>();
            var list = query.In(idList).ToList();
			if(loadRelevantData)
				Load(list);

            return list;
        }


        /// <summary>
        /// 字典数据返回
        /// </summary>
        /// <param name="method"></param>
        /// <returns></returns>
        public object GetDicList(
            Action<ISugarQueryable<Attachment>> method
		)
        {
            var query =  db.Queryable<Attachment>();
            method(query);
			var list = query.Select(m => new DicDom { label = m.name, value = m.id.ToString() }).ToArray();
            return list;
        }

        /// <summary>
        /// 查询详情
        /// </summary>
        /// <param name="method"></param>
        /// <param name="loadRelevantData">是否加载关联数据</param>
        /// <returns></returns>
        public Attachment GetEntity(
            Action<ISugarQueryable<Attachment>> method,
			bool loadRelevantData = true
		)
        {
            var query =  db.Queryable<Attachment>();
            method(query);
            Attachment model = query.First();
            if (loadRelevantData)
                Load(model);

            return model;
        }

        /// <summary>
        /// 查询详情
        /// </summary>
        /// <param name="id"></param>
        /// <param name="loadRelevantData">是否加载关联数据</param>
        /// <returns></returns>
        public Attachment GetEntity(long id, bool loadRelevantData = true)
        {
            Attachment model = db.Queryable<Attachment>().InSingle(id);
            if (loadRelevantData)
                Load(model);

            return model;
        }

        /// <summary>
        /// 根据id列表查询maps
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        public Dictionary<long, Attachment> GetMaps(List<long> idList)
        {
            var maps = new Dictionary<long, Attachment>();
            if (idList.Count < 1)
                return maps;

            var list = db.Queryable<Attachment>()
                .In(f => f.id, idList.Distinct().ToArray())
                .ToList();

            list.ForEach(m =>
            {
                maps.Add(m.id, m);
            });

            return maps;
        }

        /// <summary>
        /// 新增返回详情
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public Attachment CreateAt(Attachment model)
        {
            model.uploadTime = DateTime.Now.ToTimeStamp();
            model = db.Insertable(model).ExecuteReturnEntity();

            return GetEntity(model.id);
        }

        /// <summary>
        /// 批量新增
        /// </summary>
        /// <param name="models"></param>
        public void CreateBatch(List<Attachment> models)
        {
            if (models.IsNullOfEmpty())
                return;

            var timestamp = DateTime.Now.ToTimeStamp();
            models.ForEach(model =>
            {
                model.uploadTime = timestamp;
                model = db.Insertable(model).ExecuteReturnEntity();
            });
        }

        /// <summary>
        /// 批量新增
        /// </summary>
        /// <param name="models"></param>
        public List<Attachment> CreateBatch(int creatorId, List<DicDom> files)
        {
            if (files.IsNullOfEmpty())
                return null;

            var attachments = new List<Attachment>();
            files.ForEach(file =>
            {
                var lastIndex = file.label.LastIndexOf('.');
                var attachment = new Attachment
                {
                    uploaderId = creatorId,
                    name = file.label.Substring(0, lastIndex),
                    typeId = file.label.Substring(lastIndex + 1),
                };
                var url = file.value.ToString();
                if (url.Contains() && url.IndexOf("http") == 0)
                {
                    var uri = new Uri(url);
                    attachment.relativePath = uri.AbsolutePath;
                }
                attachments.Add(attachment);
            });
            //批量新增
            CreateBatch(attachments);

            return attachments;
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
		public Attachment UpdateAt(Attachment model) 
		{
			var rows = db.Updateable(model).IgnoreColumns(true).ExecuteCommand();

			return GetEntity(model.id);
		}

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="source"></param>
        public void DeleteAt(Attachment source)
        {
             var rows = db.Deleteable<Attachment>().In(source.id).ExecuteCommand();
            if (rows < 1)
                throw new LogicException("删除失败！");
        }


		#region 加载关联数据

        public void Load(List<Attachment> list)
        {
            if (list.IsNull())
                return;
        }

        public void Load(Attachment model)
        {
            if (model.IsNull())
                return;
        }

        #endregion


    }
}
